//
//  LatestVC.m
//  New
//
//  Created by 才诗琦 on 16/1/23.
//  Copyright © 2016年 www.lanou3g.com. All rights reserved.
//

#import "LatestVC.h"
#import "SliderView-Prefix.pch"
@interface LatestVC ()<UITableViewDataSource, UITableViewDelegate,UIGestureRecognizerDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *dataArr;/**分段最新的数组*/
@property(nonatomic, assign)UIEdgeInsets insets;
@property(nonatomic, retain)NSDictionary *expertDic;/** tableView头部区域相关信息的字典*/
@property(nonatomic, retain)NSString *str;
@property(nonatomic, retain)NSMutableArray *relateArr;/**相关新闻数组*/
@property(nonatomic, retain)UISegmentedControl *seg;/**分段控制器*/
@property(nonatomic, retain)NSMutableArray *hotListArr;/**分段最热数组*/



@end

@implementation LatestVC
- (void)viewWillAppear:(BOOL)animated
{
   self.tabBarController.tabBar.hidden = YES;
   
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.hidden = YES;
    // 设置导航默认标题的颜色及字体大小
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    

}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
     self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Nav"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor],
                                                                    NSFontAttributeName : [UIFont boldSystemFontOfSize:17]};
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
       //处理数据
    [self data];
    //tableView
    [self createTableView];
    
   //设置导航栏滚动出现
    self.automaticallyAdjustsScrollViewInsets = NO;
    if([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)])
   {
        self.automaticallyAdjustsScrollViewInsets = YES;
       self.insets = self.tableView.contentInset;
       _insets.top =28;
//       self.navigationController.navigationBar.frame.size.height;
       self.tableView.contentInset =_insets;
        self.tableView.scrollIndicatorInsets = _insets ;
       self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonClick:)];
       self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fenxiang"] style:UIBarButtonItemStylePlain target:self action:@selector(shareClick:)];
       self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
 }
}


//更新 导航栏
- (void)updateSizingWithDelta:(CGFloat)delta {
    CGRect frame = self.navigationController.navigationBar.frame;
    
   frame = self.tableView.superview.frame;
    
    frame.origin.y = self.navigationController.navigationBar.frame.origin.y;
    frame.origin.y += self.navigationController.navigationBar.frame.size.height;
    
    // 判断是否是ios7及其以上版本
    if (![self isIOS7]) {
        frame.origin.y =  self.navigationController.navigationBar.frame.origin.y - 24;
    }
    frame.size.height = frame.size.height + delta;
    self.tableView.superview.frame = frame;
    
    // Changing the layer's frame avoids UIWebView's glitchiness
    frame = self.tableView.layer.frame;
    frame.size.height += delta;
    self.tableView.layer.frame = frame;
    return;
}

- (BOOL)isIOS7 {
    return ([UIDevice currentDevice].systemVersion.integerValue >= 7) ? YES : NO;
}

#warning 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -50, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 320)];
 
    //注册cell
    [_tableView registerClass:[LatestCell class] forCellReuseIdentifier:@"QandA"];
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    [_tableView release];
    }
#warning 数据处理
- (void)data
{
    NSString *str = @"http://c.m.163.com/newstopic/qa/";
    str = [str stringByAppendingString:self.string];
    str = [str stringByAppendingString:@".html"];
    [AFNModel GETWithHandler: str completion:^(id result) {
        
        //最新数据数组
        self.dataArr =  [LatestModel modelHandlerWithArray:result[@"data"][@"latestList"]];
        self.expertDic = result[@"data"][@"expert"];
        self.relateArr = [LatestModel modelHandlerWithArray:result[@"data"][@"expert"][@"relatedNews"]];
        self.hotListArr =[LatestModel modelHandlerWithArray:result[@"data"][@"hotList"]];
        
        
        
        //导航栏标题
        self.title =_expertDic[@"alias"];
        
       
        //头图片
        UIImageView *imag = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
        [imag sd_setImageWithURL:[NSURL URLWithString:_expertDic[@"picurl"]]];
        [self.tableView addSubview:imag];
        //文字label
        UILabel *desLabel = [[UILabel alloc] init];
        desLabel.numberOfLines = 0;
        desLabel.frame = CGRectMake(50, 80, self.view.frame.size.width - 100, 60);
        desLabel.textColor = [UIColor whiteColor];
        desLabel.text = _expertDic[@"alias"];
        [imag addSubview:desLabel];
        
        //标题
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(110, 210, self.view.frame.size.width - 120, 30)];
        
        title.text = _expertDic[@"title"];
        title.textColor = [UIColor grayColor];
        [_tableView addSubview:title];
        [title release];
        
        
        //作者头像
        UIImageView *authorImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 210, 30, 30)];
        authorImageView.layer.cornerRadius = 15;
        authorImageView.clipsToBounds = YES;
        [authorImageView sd_setImageWithURL:[NSURL URLWithString:_expertDic[@"headpicurl"]]];
        [self.tableView addSubview:authorImageView];
        [authorImageView release];
        //作者名
        UILabel *authorName = [[UILabel alloc] initWithFrame:CGRectMake(40, 210, 60, 30)];
        authorName.text = _expertDic[@"name"];
        authorName.textColor = [UIColor grayColor];
        [self.tableView addSubview:authorName];
        [authorName release];
        //竖线
        
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(100, 210, 10, 30)];
        line.text = @"|";
        line.textColor = [UIColor grayColor];
        [self.tableView addSubview:line];
        
        
        //描述
        UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 240, self.view.frame.size.width - 50, 60)];
        descriptionLabel.textColor = [UIColor grayColor];
        descriptionLabel.numberOfLines = 2;
        descriptionLabel.text = _expertDic[@"description"];
        [self.tableView addSubview:descriptionLabel];
        [descriptionLabel release];
        
        [self.navigationController.navigationBar setBackgroundImage:imag.image forBarMetrics:UIBarMetricsDefault];
    //下拉显示全文按钮
        
        
        UIButton *quan = [UIButton buttonWithType:UIButtonTypeCustom];
        quan.frame = CGRectMake(100, 300, 20, 20);
        quan.center = CGPointMake(self.view.center.x, quan.center.y);
        [quan setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
        [quan addTarget:self action:@selector(quanClick:) forControlEvents:UIControlEventTouchUpInside];
 [self.tableView addSubview:quan];
        
        
        
        
        
        //整体刷新
        [_tableView reloadData];
    }];
    
}

#warning 按钮点击事件
- (void)quanClick:(UIButton *)bu
{
    
}


#warning 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_relateArr.count != 0) {
        return 2;
    }
        
else
    return 1;
    
}
#warning 自定义头部区域

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 50, 375, 30)];

    UIImageView *gray = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 375, 30)];
        [gray setImage:[UIImage imageNamed:@"hui"]];
        [header addSubview:gray];
    
    
        
    
    if (section == 0 && _relateArr.count != 0) {
        
        
              UIImageView *xinWen = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 20, 20)];
        [xinWen setImage:[UIImage imageNamed:@"xinwendongtai"]];
        [gray addSubview:xinWen];
        [xinWen release];
        
        UILabel *la = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 300, 30)];
        la.text = @"相关新闻";
        [gray addSubview:la];
        [la release];
    
    }
    else  {
        //创建分段控制器
      self.seg = [[UISegmentedControl alloc] initWithItems:@[@"最新", @"最热"]];
//        设置frame
        self.seg.frame = CGRectMake(self.view.frame.size.width - 100, 5, 80, 20);
        //背景颜色
//        self.seg.backgroundColor = [UIColor whiteColor];
        //点击颜色
        self.seg.tintColor = [UIColor redColor];
        //分段索引
        self.seg.selectedSegmentIndex = 0;
        
        //添加点击事件
        
        
       //添加父视图
        
        [header addSubview:self.seg];
       //提问数
        UILabel *q = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        q.text = [_expertDic[@"questionCount"] stringValue];
        [header addSubview:q];
        [q release];
        UILabel *qu = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 40, 30)];
        qu.text = @"提问";
        [gray addSubview:qu];
        [qu release];
        //点
        UILabel *point = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, 10, 30)];
        point.text = @"·";
        [gray addSubview:point];
        [point release];
        
        //回答数
        UILabel *a = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 30, 30)];
        a.text = [_expertDic[@"answerCount"] stringValue];
        [gray addSubview:a];
        [a release];
        UILabel *an = [[UILabel alloc] initWithFrame:CGRectMake(130, 0, 40, 30)];
        an.text = @"回复";
        [gray addSubview:an];
        [an release];
        //进行中
        UILabel *j = [[UILabel alloc] initWithFrame:CGRectMake(180, 0, 60, 30)];
        j.text = @"进行中";
        [gray addSubview:j];
        [j release];
        
    }
    return  [header autorelease];
}


//头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

#warning cell设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 && _relateArr.count != 0) {
        return _relateArr.count;
    }
    
   else
   {
       if (self.seg.selectedSegmentIndex == 0) {
           return _dataArr.count;
       }
       
       else{
           return _hotListArr.count;
       }
       }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && _relateArr.count != 0) {
        LatestModel *la = _relateArr[indexPath.row];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        cell.textLabel.text = la.title;
        return cell;
        
    }
    else{
        LatestCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QandA" forIndexPath:indexPath];
        if (self.seg.selectedSegmentIndex == 0) {
             LatestModel *latest = _dataArr[indexPath.row];
        
    
   
    cell.quesLabel.text = latest.question[@"content"];
    [cell.quesUser sd_setImageWithURL:[NSURL URLWithString:latest.question[@"userHeadPicUrl"]]];
    cell.quesUserNameLabel.text = latest.question[@"userName"];
    
    cell.ansLabel.text = latest.answer[@"content"];
    [cell.ansUser sd_setImageWithURL:[NSURL URLWithString:latest.answer[@"specialistHeadPicUrl"]] placeholderImage:[UIImage imageNamed:@"icon"]];
    cell.ansUserNameLabel.text = latest.answer[@"specialistName"];
    cell.likeCount.text = [latest.answer[@"supportCount"] stringValue];
            
            return cell;}
    else
    {
    
        LatestModel *latest = _hotListArr[indexPath.row];
        
        
        
        cell.quesLabel.text = latest.question[@"content"];
        [cell.quesUser sd_setImageWithURL:[NSURL URLWithString:latest.question[@"userHeadPicUrl"]]];
        cell.quesUserNameLabel.text = latest.question[@"userName"];
        
        cell.ansLabel.text = latest.answer[@"content"];
        [cell.ansUser sd_setImageWithURL:[NSURL URLWithString:latest.answer[@"specialistHeadPicUrl"]] placeholderImage:[UIImage imageNamed:@"icon"]];
        cell.ansUserNameLabel.text = latest.answer[@"specialistName"];
        cell.likeCount.text = [latest.answer[@"supportCount"] stringValue];
        
        return cell;
    
    }
   
    
    }
    
    
}
//cell高度设置
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && _relateArr.count != 0) {
        
        
        return 40;
    }
    else{
        
        if (self.seg.selectedSegmentIndex == 0) {
            
        
    LatestModel *latest = _dataArr[indexPath.row];
    
    CGFloat h = [LatestCell heightWithTextQ:latest.question[@"content"]];
    CGFloat h1 = [LatestCell heightWithTextA:latest.answer[@"content"]];
    
        return h + h1+ 170;
        }
        else{
            
            LatestModel *latest = _hotListArr[indexPath.row];
            
            CGFloat h = [LatestCell heightWithTextQ:latest.question[@"content"]];
            CGFloat h1 = [LatestCell heightWithTextA:latest.answer[@"content"]];
            
            return h + h1+ 170;
            
        }
    }
}
#warning 导航栏显示或隐藏设置
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset

{
    if (velocity.y > 0) {
        [UIView animateWithDuration:0.5 animations:^{
            CGRect frame;
            frame = self.navigationController.navigationBar.frame;
            CGFloat delta = frame.origin.y - 20;
            frame.origin.y = MIN(20, frame.origin.y - delta);
            self.navigationController.navigationBar.frame = frame;
          self.navigationController.navigationBar.hidden = NO;

          
            [self updateSizingWithDelta:delta];
        }];
    } else {
        
        [UIView animateWithDuration:0.5 animations:^{
            CGRect frame;
            frame = self.navigationController.navigationBar.frame;
            CGFloat delta = frame.origin.y + 24;
            frame.origin.y = MAX(-24, frame.origin.y - delta);
            self.navigationController.navigationBar.frame = frame;
            self.navigationController.navigationBar.hidden = YES;
           [self updateSizingWithDelta:delta];
        }];
    }
    return;
}
//返回按钮点击方法
- (void)buttonClick:(UIButton *)button
{
    
    [self.navigationController popViewControllerAnimated:YES];
   
}
#warning 分享按钮点击方法
- (void)shareClick:(UIButton *)share
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
